package com.fa4j.third.base.adapter;

import com.fa4j.third.base.model.ThirdBizProps;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.ReflectionUtils;

import java.io.Closeable;
import java.io.IOException;

public abstract class AbstractThirdServiceAdapter implements Closeable {

    @Setter
    @Getter
    private ThirdBizProps props;

    @Override
    public void close() throws IOException {

    }


    /**
     * 初始化
     */
    public void init() {
        if (props.getAdapterParams() != null) {
            ReflectionUtils.doWithFields(this.getClass(), field -> {
                if (props.getAdapterParams().containsKey(field.getName())) {
                    field.setAccessible(true);
                    Object value = parseFieldValue(props.getAdapterParams().get(field.getName()), field.getType());
                    if (value != null) {
                        ReflectionUtils.setField(field, this, value);
                    }
                }
            });
        }
    }
    
    private Object parseFieldValue(String str, Class<?> type) {
        if (type == String.class || str == null) {
            return str;
        }
        if (type == Boolean.class || type == boolean.class) {
            return Boolean.parseBoolean(str);
        }
        if (type == Integer.class || type == int.class) {
            return Integer.parseInt(str);
        }
        if (type == Long.class || type == long.class) {
            return Long.parseLong(str);
        }
        if (type == Double.class || type == double.class) {
            return Double.parseDouble(str);
        }
        if (type == Float.class || type == float.class) {
            return Float.parseFloat(str);
        }
        return null;
    }
}
